package com.ysyx.ysyx_ordersetstatu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysyx.ysyx_ordersetstatu.dto.BaseDto;
import com.ysyx.ysyx_ordersetstatu.mapper.OrderdetailPojoMapper;
import com.ysyx.ysyx_ordersetstatu.pojo.OrderPojo;
import com.ysyx.ysyx_ordersetstatu.pojo.OrderdetailPojo;
import com.ysyx.ysyx_ordersetstatu.qo.DriverCancelQo;
import com.ysyx.ysyx_ordersetstatu.qo.EndorderQo;
import com.ysyx.ysyx_ordersetstatu.qo.PassengerCancelQo;
import com.ysyx.ysyx_ordersetstatu.qo.SuretelQo;
import com.ysyx.ysyx_ordersetstatu.service.OrderPojoService;
import com.ysyx.ysyx_ordersetstatu.mapper.OrderPojoMapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 *
 */
@Service
public class OrderPojoServiceImpl extends ServiceImpl<OrderPojoMapper, OrderPojo>
    implements OrderPojoService{

    @Autowired
    private OrderPojoMapper orderPojoMapper;

    @Autowired
    private OrderdetailPojoMapper orderdetailPojoMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public BaseDto suretel(SuretelQo suretelQo) {
        System.out.println("OrderPojoServiceImpl.suretel="+suretelQo.toString());

        String orderPassengerTel = orderPojoMapper.getOrderPassengerTel(suretelQo.getOrderId());
        if(orderPassengerTel.length()>4){
            System.out.println(orderPassengerTel);
            String lastFourNum = orderPassengerTel.substring(orderPassengerTel.length()-4,orderPassengerTel.length());

            if(lastFourNum.equals(suretelQo.getLastFourNum())){
                System.out.println("手机后四位匹配成功");
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(System.currentTimeMillis());
                String format = formatter.format(date);
                System.out.println(format);

                //
                //查询orderId orderdetailPojo
                QueryWrapper<OrderdetailPojo> orderdetailQw = new QueryWrapper<>();
                orderdetailQw.eq("order_id",suretelQo.getOrderId());
                OrderdetailPojo orderdetailPojo = orderdetailPojoMapper.selectOne(orderdetailQw);

                //
                //查询orderId的 orderPojo
//                QueryWrapper<OrderPojo> orderQw = new QueryWrapper<>();
//                orderQw.eq("order_Id",suretelQo.getOrderId());
//                OrderPojo orderPojo = orderPojoMapper.selectOne(orderQw);

                //order_inf 添加司机Id,修改数据库订单状态,修改订单状态时间
                UpdateWrapper<OrderPojo> orderUw = new UpdateWrapper<>();
                orderUw.eq("order_id",suretelQo.getOrderId())
//                        .set("driver_id",suretelQo.getDriverId())
                        .set("order_status",403)
                        .set("order_statustime",format);
                orderPojoMapper.update(null,orderUw);

                //orderdetail_inf 添加行程开始时间
                UpdateWrapper<OrderdetailPojo> orderdetailUw = new UpdateWrapper<>();
                orderdetailUw.eq("orderdetail_id",orderdetailPojo.getOrderdetailId()).set("start_time",format);
                orderdetailPojoMapper.update(null, orderdetailUw);

                //修改Redis中订单状态
                RMap<Object, Object> orderinfoMap = redissonClient.getMap("orderinfo:" + suretelQo.getOrderId());
                orderinfoMap.put("orderStatus",403);
                orderinfoMap.put("orderStatustime",format);
                return new BaseDto(101,"手机后四位匹配成功，订单开始行程",null);
            }else{
                return new BaseDto(201,"手机四位匹配失败",null);
            }
        }else{
            return new BaseDto(301,"手机后四位长度错误",null);
        }

//        return new BaseDto(0,suretelQo.toString(),null);
    }

    @Override
    public BaseDto endorder(EndorderQo endorderQo) {
        //获取时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String format = formatter.format(date);

        //修改orderPojo 状态，修改orderPojo 状态时间
        UpdateWrapper<OrderPojo> orderUw = new UpdateWrapper<>();
        orderUw.eq("order_id",endorderQo.getOrderId()).set("order_status",601).set("order_statustime",format);
        orderPojoMapper.update(null,orderUw);

        //修改orderdetailPojo状态
        UpdateWrapper<OrderdetailPojo> orderdetailUw = new UpdateWrapper<>();
        orderdetailUw.eq("order_id",endorderQo.getOrderId()).set("end_time",format);
        orderdetailPojoMapper.update(null,orderdetailUw);

        //修改Redis中订单状态
        RMap<Object, Object> orderinfoMap = redissonClient.getMap("orderinfo:" + endorderQo.getOrderId());
        orderinfoMap.put("orderStatus",601);
        orderinfoMap.put("orderStatustime",format);

        //该服务没有为结束司机进行定位

        //司机从上工池移除
        RSet<Object> workingDriver = redissonClient.getSet("working:driver");
        boolean removeFlag = workingDriver.remove(endorderQo.getDriverId());
        System.out.println("endorderQo=="+endorderQo.toString());
        System.out.println("workmove=="+removeFlag);

        if(removeFlag){
            //司机添加到上工司机待命池
            RBucket<Object> workDriver = redissonClient.getBucket("work:driver");
            workDriver.set(endorderQo.getDriverId());
        }

        return new BaseDto(101,"订单已结束",null);
    }


    //乘客取消订单
    @Override
    public BaseDto passengerCancel(PassengerCancelQo passengerCancelQo) {

        RMap<Object,Object> orderinfoMap = redissonClient.getMap("orderinfo:"+passengerCancelQo.getOrderId());
        //先查看redis中的订单消息

        String driverId = (String) orderinfoMap.get("driverId");
        if(driverId == null){
            System.out.println("driver不存在，没有司机接单");
            //修改订单状态  订单长时间没有司机接单,乘客取消订单	201
            orderinfoMap.put("orderStatus",201);
            rocketMQTemplate.convertAndSend("order:passengerCancel","201&"+passengerCancelQo.getOrderId());
        }else{

            //修改订单状态 司机前往起点，乘客取消订单	302
            System.out.println("driver当前司机id="+driverId);
            orderinfoMap.put("orderStatus",302);
            rocketMQTemplate.convertAndSend("order:passengerCancel","302&"+passengerCancelQo.getOrderId());
        }

        for(Map.Entry<Object,Object>entry:orderinfoMap.entrySet()){
            System.out.println("Key="+entry.getKey()+",Value="+entry.getValue());
        }

        RSet<Object> set = redissonClient.getSet("working:driver");
        set.remove(driverId);
        RBucket<Object> bucket = redissonClient.getBucket("work:driver:" + driverId);
        bucket.set(driverId);


        return new BaseDto(100,passengerCancelQo.toString(),null);
    }



    //司机取消订单
    @Override
    public BaseDto driverCancel(DriverCancelQo driverCancelQo) {
        System.out.println("数据");
        System.out.println(driverCancelQo);

        RMap<Object,Object> orderinfoMap = redissonClient.getMap("orderinfo:"+driverCancelQo.getOrderId());
        //先查看redis中的订单消息
//        for(Map.Entry<Object,Object>entry:orderinfoMap.entrySet()){
//            System.out.println("Key="+entry.getKey()+",Value="+entry.getValue());
//        }
        RSet<Object> set = redissonClient.getSet("working:driver");
        set.remove(driverCancelQo.getDriverId());
        RBucket<Object> bucket = redissonClient.getBucket("work:driver:" + driverCancelQo.getDriverId());
        bucket.set(driverCancelQo.getDriverId());


        rocketMQTemplate.convertAndSend("order:driverCancel",driverCancelQo.getOrderId());
        return new BaseDto(100,driverCancelQo.toString(),null);
    }

    @Override
    public BaseDto driverCancelDaoMQ(String orderId) {
        //补充对redis的操作
        RMap<Object, Object> map = redissonClient.getMap("orderinfo:" + orderId);
        map.put("orderStatus",303);
        boolean remove = redissonClient.getSet("tense:order").remove(orderId);
        System.err.println(remove);


        UpdateWrapper<OrderPojo> orderUw = new UpdateWrapper<>();
        orderUw.eq("order_id",orderId).set("order_status",303);



        System.out.println("Service当前MQ的status为="+303);
        System.out.println("Service司机取消订单为="+orderId);
        orderPojoMapper.update(null,orderUw);
        return null;
    }

    @Override
    public BaseDto passengerCancelDaoMQ(String orderInfo) {

        String status = orderInfo.split("&")[0];
        String orderId = orderInfo.split("&")[1];

        boolean remove = redissonClient.getSet("tense:order").remove(orderId);
        System.err.println(remove);

        System.out.println("Service当前MQ的status为="+status);
        System.out.println("Service乘客取消订单为="+orderId);

        UpdateWrapper<OrderPojo> orderUw = new UpdateWrapper<>();
        orderUw.eq("order_id",orderId).set("order_status",Integer.valueOf(status));
        orderPojoMapper.update(null,orderUw);
        return null;
    }


}




